import React from 'react';
import { Button, message} from 'antd';
import Grid from '../../components/table/grid';
import SCModal from '../../components/pickCity/SCModal';
import {injectIntl} from 'react-intl';
import axios from "axios/index";


class bindVIN extends React.Component {
    constructor(props) {
        super(props);
        this.common = this.props.intl.messages.common;
        this.state = {
            selectedStations: [],
            refresh:0
        };
        this.columns4VIN = [
            {
                title: this.common.powerStationName,
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: this.common.operation,
                key: 'action',
                render: (text, record) => (
                    <span>
                        <a onClick={() => this.bindVIN(text, record)}>{this.common.bind}</a>
                    </span>
                )
            }
        ];
    }
    componentWillReceiveProps(nextProps) {
        if(nextProps.visible){
            this.setState({
                refresh:this.state.refresh+1
            })
        }
    }

    bindVIN = (text) => {
        const vins = this.props.selectedRowKeys.map(k => (k.vin)).join(',');
        this.fetchData({stubGroupIds: text.id, vins: vins}, '/api/vinStub/bindStub');
    };

    batchBind = () => {
        if (this.state.selectedStations.length === 0) {
            message.warn('请选择电站');
            return
        }
        const selectedStations = this.state.selectedStations.join(',');
        const vins = this.props.selectedRowKeys.map(k => (k.vin)).join(',');
        console.log(vins, selectedStations);
        this.fetchData({stubGroupIds: selectedStations, vins: vins}, '/api/vinStub/bindStub');
    };


    fetchData = (params, url) => {
        axios.get(url, {params: params}).then(res => {
            console.log(res);
            if (res && res.data && res.data.code == '200') {
                message.success('操作成功');
                this.props.handleCancel();
            }
        })
    };

    render() {
        const rowSelection4VIN = {
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedStations: selectedRowKeys
                }, () => {
                    console.log(this.state)
                })
            },
        };
        return (
            <SCModal visible={this.props.visible} handleCancel={this.props.handleCancel} title={this.common.chooseStub}>
                <Button type="primary" onClick={this.batchBind}
                        style={{marginBottom: 20}}>{this.common.batchBind}</Button>
                <Grid rowSelection={rowSelection4VIN} refresh={this.state.refresh}
                      columns={this.columns4VIN} url="/api/plan/stubGroup/qry"/>
            </SCModal>
        )
    }
}

export default injectIntl(bindVIN);